package com.atcjx.MyUtils.File;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.atcjx.MyUtils.ResultFactory;
import com.atcjx.exception.UserException;
import com.atcjx.exception.exceptionEnum;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName UploadGiteeImgBed.java
 * @Description 配置码云图床信息
 * @createTime 2021年10月08日 19:48:00
 */
public class UploadGiteeImgBed {
    /*
    * 码云的私人令牌
    * */
    public static final String ACCESS_TOKEN = "228c5d98907f7c1761c69cce5a0a5d3a";

    /*
    * 码云的个人空间名称
    * */
    public static final String OWNER="Cjx_723";
    /*
    * 上传至指定的仓库
    * */
    public static final String REPO="my-pic-warehouse";

    /**
     * 上传时指定存放图片路径
     */
    public static final String PATH = "/uploadimg/" + DateUtil.date().getYear() + "/" + DateUtil.date().getMonth() + "/"; //使用到了日期工具类

    /**
     * 用于提交描述
     */
    public static final String ADD_MESSAGE = "add img";
    public static final String DEL_MESSAGE = "DEL img";

    //API
    /**
     * 新建(POST)、获取(GET)、删除(DELETE)文件：()中指的是使用对应的请求方式
     * %s =>仓库所属空间地址(企业、组织或个人的地址path)  (owner)
     * %s => 仓库路径(repo)
     * %s => 文件的路径(path)
     */
    public static final String API_CREATE_POST = "https://gitee.com/api/v5/repos/%s/%s/contents/%s";

    /**
     * 生成创建(获取、删除)的指定文件路径,返回路径名称
     * @param originalFilename
     * @return
     */
    public static String createUploadFileUrl(String originalFilename){
        //获取文件后缀
        String suffix = FileUtils.fileSuffix(originalFilename);//使用到了自己编写的FileUtils工具类
        //拼接存储的图片名称
        String fileName = System.currentTimeMillis()+"_"+ UUID.randomUUID() +suffix;
        //填充请求路径
        String url = String.format(UploadGiteeImgBed.API_CREATE_POST,
                UploadGiteeImgBed.OWNER,
                UploadGiteeImgBed.REPO,
                UploadGiteeImgBed.PATH+fileName);
        return url;
    }

    /**
     * 获取创建文件的请求体map集合：access_token、message、content
     * @param multipartFile 文件字节数组
     * @return 封装成map的请求体集合
     */
    public static Map<String,Object> getUploadBodyMap(byte[] multipartFile){
        HashMap<String, Object> bodyMap = new HashMap<>(3);
        bodyMap.put("access_token",UploadGiteeImgBed.ACCESS_TOKEN);
        bodyMap.put("message", UploadGiteeImgBed.ADD_MESSAGE);
        bodyMap.put("content", Base64.encode(multipartFile));
        return bodyMap;
    }
    /**
     * 描述：上传图片到Gitee图床
     * @author 崔杰翔
     * @Date 2021/10/9 14:23
     * @param multipartFile
     * @return java.lang.String
     */
    public static String uploadToGiteePicBed(MultipartFile multipartFile) throws IOException {
        String originalFileName=multipartFile.getOriginalFilename();
        if(originalFileName==null){
            throw new UserException(exceptionEnum.NULLFILENAME.getMsg(), exceptionEnum.NULLFILENAME.getCode());
        }
        //获取url
        String targetURL=UploadGiteeImgBed.createUploadFileUrl(originalFileName);
        byte[] bytes = multipartFile.getBytes();
        System.out.println("压缩前的大小" + bytes.length);
        byte[] compressed = PicUtils.compressUnderSize(bytes, (long) (1024 * 1024* 1.4));
        System.out.println("压缩后的大小"+compressed.length);
        // 封装请求体
        Map<String, Object> uploadBodyMap = UploadGiteeImgBed.getUploadBodyMap(compressed);
        //发送Post请求并响应参数
        String JSONResults = HttpUtil.post(targetURL, uploadBodyMap);
        //解析字符串
        JSONObject jsonObject = JSONUtil.parseObj(JSONResults);
        //请求失败
        if(jsonObject==null||jsonObject.getObj("commit")==null){
            throw new UserException(exceptionEnum.UPLOADERROR.getMsg(), exceptionEnum.UPLOADERROR.getCode());
        }
        JSONObject content = JSONUtil.parseObj(jsonObject.getObj("content"));
        return content.getObj("download_url").toString();
    }
    /**
     * 描述：上传图片到Gitee图床，通过URL连接的方式
     * @author 崔杰翔
     * @Date 2021/10/9 14:23
     * @param targetURL
     * @return java.lang.String
     */
    public static String uploadToGiteePicBedByUrl(String targetURL) throws Exception {
        MultipartFile file = FileUtils.urlToMultipartFile(targetURL);
        return uploadToGiteePicBed(file);
    }

}
